<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>待办事项管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .input-group {
            display: flex;
            margin-bottom: 20px;
            gap: 10px;
        }
        input[type="text"] {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        .todo-list {
            list-style: none;
            padding: 0;
        }
        .todo-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #eee;
            gap: 10px;
        }
        .todo-item.completed {
            background-color: #f9f9f9;
        }
        .todo-item.completed .todo-title {
            text-decoration: line-through;
            color: #888;
        }
        .todo-title {
            flex: 1;
        }
        .todo-time {
            font-size: 12px;
            color: #888;
            margin-right: 10px;
        }
        .error {
            color: red;
            margin-bottom: 10px;
        }
        .success {
            color: green;
            margin-bottom: 10px;
        }
        .filters {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .filter-btn {
            background-color: #ddd;
        }
        .filter-btn.active {
            background-color: #4CAF50;
        }
        .search-container {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>待办事项管理系统</h1>
        
        <div class="search-container">
            <div class="input-group">
                <input type="text" id="searchInput" placeholder="搜索待办事项...">
                <button onclick="searchTodos()">搜索</button>
            </div>
        </div>

        <div class="input-group">
            <input type="text" id="todoInput" placeholder="输入新的待办事项...">
            <button onclick="addTodo()">添加</button>
        </div>

        <div class="filters">
            <button class="filter-btn active" onclick="filterTodos('all')">全部</button>
            <button class="filter-btn" onclick="filterTodos('active')">未完成</button>
            <button class="filter-btn" onclick="filterTodos('completed')">已完成</button>
        </div>

        <div id="message" class=""></div>
        <ul id="todoList" class="todo-list"></ul>
    </div>

    <script>
        let todos = [];
        let currentFilter = 'all';

        // 获取所有待办事项
        async function fetchTodos(search = '') {
            try {
                const response = await fetch(`/api/todos${search ? `?search=${search}` : ''}`);
                todos = await response.json();
                renderTodos();
            } catch (error) {
                showMessage('获取待办事项失败', 'error');
            }
        }

        // 添加新待办事项
        async function addTodo() {
            const input = document.getElementById('todoInput');
            const title = input.value.trim();
            
            if (!title) {
                showMessage('请输入待办事项内容', 'error');
                return;
            }

            try {
                const response = await fetch('/api/todos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ title }),
                });

                if (response.ok) {
                    input.value = '';
                    showMessage('添加成功', 'success');
                    fetchTodos();
                } else {
                    showMessage('添加失败', 'error');
                }
            } catch (error) {
                showMessage('添加失败', 'error');
            }
        }

        // 删除待办事项
        async function deleteTodo(id) {
            try {
                const response = await fetch(`/api/todos/${id}`, {
                    method: 'DELETE',
                });

                if (response.ok) {
                    showMessage('删除成功', 'success');
                    fetchTodos();
                } else {
                    showMessage('删除失败', 'error');
                }
            } catch (error) {
                showMessage('删除失败', 'error');
            }
        }

        // 更新待办事项
        async function updateTodo(id, updates) {
            try {
                const response = await fetch(`/api/todos/${id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(updates),
                });

                if (response.ok) {
                    showMessage('更新成功', 'success');
                    fetchTodos();
                } else {
                    showMessage('更新失败', 'error');
                }
            } catch (error) {
                showMessage('更新失败', 'error');
            }
        }

        // 标记待办事项状态
        function toggleTodo(id) {
            const todo = todos.find(t => t.id === id);
            if (todo) {
                updateTodo(id, { completed: todo.completed ? 0 : 1 });
            }
        }

        // 编辑待办事项
        function editTodo(id) {
            const todo = todos.find(t => t.id === id);
            if (todo) {
                const newTitle = prompt('编辑待办事项:', todo.title);
                if (newTitle !== null && newTitle.trim() !== '') {
                    updateTodo(id, { title: newTitle.trim() });
                }
            }
        }

        // 搜索待办事项
        function searchTodos() {
            const searchInput = document.getElementById('searchInput');
            const searchTerm = encodeURIComponent(searchInput.value.trim());
            fetchTodos(searchTerm);
        }

        // 筛选待办事项
        function filterTodos(filter) {
            currentFilter = filter;
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.textContent.includes(filter === 'all' ? '全部' : 
                    filter === 'active' ? '未完成' : '已完成')) {
                    btn.classList.add('active');
                }
            });
            renderTodos();
        }

        // 渲染待办事项列表
        function renderTodos() {
            const todoList = document.getElementById('todoList');
            todoList.innerHTML = '';

            const filteredTodos = todos.filter(todo => {
                if (currentFilter === 'active') return !todo.completed;
                if (currentFilter === 'completed') return todo.completed;
                return true;
            });

            filteredTodos.forEach(todo => {
                const li = document.createElement('li');
                li.className = `todo-item${todo.completed ? ' completed' : ''}`;
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.checked = todo.completed;
                checkbox.onclick = () => toggleTodo(todo.id);
                
                const title = document.createElement('span');
                title.className = 'todo-title';
                title.textContent = todo.title;
                title.ondblclick = () => editTodo(todo.id);
                
                const time = document.createElement('span');
                time.className = 'todo-time';
                time.textContent = new Date(todo.created_at).toLocaleString();
                
                const editBtn = document.createElement('button');
                editBtn.textContent = '编辑';
                editBtn.onclick = () => editTodo(todo.id);
                
                const deleteBtn = document.createElement('button');
                deleteBtn.textContent = '删除';
                deleteBtn.onclick = () => deleteTodo(todo.id);
                
                li.appendChild(checkbox);
                li.appendChild(title);
                li.appendChild(time);
                li.appendChild(editBtn);
                li.appendChild(deleteBtn);
                
                todoList.appendChild(li);
            });
        }

        // 显示消息
        function showMessage(text, type) {
            const message = document.getElementById('message');
            message.textContent = text;
            message.className = type;
            setTimeout(() => {
                message.textContent = '';
                message.className = '';
            }, 3000);
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            fetchTodos();
            
            // 添加回车键监听
            document.getElementById('todoInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') addTodo();
            });
            
            document.getElementById('searchInput').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') searchTodos();
            });
        });
    </script>
</body>
</html> 